package com.tjetc.service.impl;

import com.tjetc.dao.AdoptApplicationMapper;
import com.tjetc.dao.AnimalMapper;
import com.tjetc.dao.HistoryMapper;
import com.tjetc.domain.AdoptionApplication;
import com.tjetc.domain.Animal;
import com.tjetc.domain.History;
import com.tjetc.service.ApplicationManageService;
import com.tjetc.utils.Db;
import com.tjetc.vo.Result;

import java.time.LocalDateTime;

public class ApplicationManageServiceImpl implements ApplicationManageService {
    private AnimalMapper animalMapper=Db.getMapper(AnimalMapper.class);
    private HistoryMapper historyMapper=Db.getMapper(HistoryMapper.class);
    private AdoptApplicationMapper adoptApplicationMapper= Db.getMapper(AdoptApplicationMapper.class);
    @Override
    public Result list() {
        return new Result(200,null,adoptApplicationMapper.list());
    }

    @Override
    public Result approval(AdoptionApplication application) {
        AdoptionApplication application1= adoptApplicationMapper.getApprovalById(application.getId());
        if (application1!=null){
            application.setStatus(1);
            application.setApprovalTime(LocalDateTime.now());
            int rows=adoptApplicationMapper.update(application);
            if (rows==1){
                animalMapper.update(new Animal().setAdopted(1).setId(application1.getAnimalId()));
                historyMapper.insert(new History().setAdopterId(application1.getAdopterId()).setAnimalId(application1.getAnimalId()).setAdoptionTime(LocalDateTime.now()));
                return new Result(200,"批准成功",null);
            }else {
                return new Result(500,"批准失败",null);
            }
        }
        return new Result(500,"没有该申请",null);
    }

    @Override
    public Result refuse(AdoptionApplication application) {
        AdoptionApplication application1= adoptApplicationMapper.getApprovalById(application.getId());
        if (application1!=null){
            application.setStatus(2);
            int rows=adoptApplicationMapper.update(application);
            if (rows==1){
                animalMapper.update(new Animal().setAdopted(0).setId(application1.getAnimalId()));
                return new Result(200,"拒绝成功",null);
            }else {
                return new Result(500,"拒绝失败",null);
            }
        }
        return new Result(500,"没有该申请",null);
    }

    @Override
    public Result listAllHistory() {
        return new Result(200,null,historyMapper.listHistory(null));
    }
}
